const puppeteer=require("puppeteer")
const ora=require("ora")
const spinner = ora('正在运行中...').start();

spinner.text = 'loading...';

let params = {
    username: "",
    password: "",
    address: "",
}

async function start(query) {
    params = query
    const browser = await puppeteer.launch({
        headless: true,
        defaultViewport: {
            width: 1920,
            height: 1080,
        },
    })
    const page = await browser.newPage()
    clickAccept(page)//监听弹框，默认确认
    await page.goto("https://gitee.com/login")

    await gitee_login(page)//登陆
    await page.goto(params.address)
    await awaitAndClick(".button.update_deploy", page)
    await page.waitForSelector(".ui.active.inline.loader.deploying_loading", page)
    const isFalse = await isLoop(".ui.active.inline.loader.deploying_loading", page)//循环判断loding是否存在，不存在则更新成功
    if (!isFalse) {
        spinner.succeed("更新成功")
        // console.log("更新成功")
        await browser.close();
    }
}
function gitee_login(page) {
    return new Promise(async resolve => {
        await page.goto("https://gitee.com/login")
        await page.waitForSelector("#user_login")
        await page.waitForSelector("#user_password")
        await page.type("#user_login", params.username);
        await page.type("#user_password", params.password);
        await page.click('input[type="submit"]')
        await page.waitForNavigation()
        console.log("登陆成功")
        resolve(true)
    })
}

function awaitAndClick(selector, page) {
    return new Promise(async resolve => {
        await page.waitForSelector(selector)
        await page.click(selector)
        resolve(true)
    })
}

function isLoop(selector, page) {
    return new Promise(async resolve => {
        setTimeout(async () => {
            const searchInputs = await page.$(selector);
            if (searchInputs) {
                resolve(isLoop(selector, page))
            } else {
                resolve(false)
            }
        }, 1000)
    })
}


function clickAccept(page) {
    return new Promise(async resolve => {
        await page.on("dialog", async dialog => {
            await dialog.accept()
            resolve(true)
        })
    })
}


module.exports = start